<script setup>
import { Sort, Tickets, CircleClose } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
// import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import {
  GetTaskService,
  ChangeTaskService,
  DelTaskService,
  GetResultTaskService,
  GetDetailTaskService
} from '@/api/task.js'
import { GetNodeByName } from '@/api/node.js'
import { GetAlgorithmDetailService } from '@/api/algorithm.js'
import AddTask from '@/views/node/components/AddTask.vue'
import nodeInfo from '@/views/node/components/nodeInfo.vue'
import taskInfo from '@/views/node/components/taskInfo.vue'
// const route = useRoute()
const useStore = useUserStore()

// 接收node.vue传过来的节点信息参数
// const nodeId = route.query.id
// const nodeName = route.query.name
// const nodeMode = route.query.mode
// const nodeAddr = route.query.addr
// const nodeStatus = route.query.status
// const nodeSource = route.query.source

const selectedNode = ref({})

// 算法信息
const alg = ref({
  id: '',
  name: '',
  mode: '',
  model: '',
  outAddr: '',
  sources: []
})
const params = ref({
  current: 1, // 当前页
  size: 5, // 当前生效的每页条数
  nodeId: -1,
  timePeriod: 1000,
  stat: '全部状态'
})

// 任务时间段选项
const options1 = [
  {
    value: 1000,
    label: '全部时间'
  },
  {
    value: 1,
    label: '最近一小时'
  },
  {
    value: 24,
    label: '最近一天'
  },
  {
    value: 24 * 3,
    label: '最近三天'
  },
  {
    value: 24 * 7,
    label: '最近七天'
  }
]

//  任务状态选项
const options2 = [
  {
    value: '全部状态',
    label: '全部状态'
  },
  {
    value: 'running',
    label: 'running'
  },
  {
    value: 'end',
    label: 'end'
  },
  {
    value: 'pending',
    label: 'pending'
  },
  {
    value: 'timeout',
    label: 'timeout'
  },
  {
    value: 'error',
    label: 'error'
  }
]

// 任务列表
const channelList = ref([{}])

// 得到任务列表
const total = ref(0)
const pages = ref(0)
const loading = ref(false)
const getChannelList = async () => {
  loading.value = true
  console.log(params.value)

  const { data } = await GetTaskService(params.value)
  loading.value = false
  console.log(data)

  channelList.value = data.data.list // 直接赋值为数组
  selectedTask.value = channelList.value ? channelList.value[0] : ''
  total.value = data.data.total
  pages.value = Math.ceil(total.value / params.value.size) // 使用 Math.ceil 确保分页正确
}

// 获取算法基本信息
const getAlgDetail = async () => {
  const { data } = await GetAlgorithmDetailService(selectedNode.value.id)
  alg.value = data.data
}

// 筛选事件
const handleChange = () => {
  params.value.current = 1
  getChannelList()
}

//被选中的任务
const selectedTask = ref(channelList.value[0])
const activeIndex = ref(0)

//点击查看任务详情信息
const taskInfos = ref([])
const showMore = async (item, index) => {
  const { data } = await GetResultTaskService(item.id)
  taskInfos.value = data.data
  const res = await GetDetailTaskService(item.id)
  selectedTask.value = res.data.data
  activeIndex.value = index
}

// 切换优先级，向上切换
const onRowClick = async (item) => {
  await ChangeTaskService(item.id)
  const { data } = await GetDetailTaskService(item.id)
  selectedTask.value = data.data
  ElMessage.success('提高等级成功')
}
const currentRowKey = ref(1)

onMounted(() => {
  currentRowKey.value =
    channelList.value.length > 0 ? channelList.value[0].name : null
})

// 处理分页逻辑
const onSizeChange = (size) => {
  // 只要是每页条数变化了，那么原本正在访问的当前页意义不大了，数据大概率已经不在原来那一页了
  // 重新从第一页渲染即可
  params.value.current = 1
  params.value.size = size
  // 基于最新的当前页 和 每页条数，渲染数据
  getChannelList()
}
const onCurrentChange = (page) => {
  // 更新当前页
  params.value.current = page
  // 基于最新的当前页，渲染数据
  getChannelList()
}

// 取消执行任务逻辑（删除）
const onTerminateTask = async (id) => {
  await ElMessageBox.confirm('你确认要取消执行该任务么', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  await DelTaskService(id)
  ElMessage.success('取消执行成功')
  getChannelList()
}

//查看节点信息
const nodeInfoRef = ref()
const infoSearch = () => {
  nodeInfoRef.value.open(alg.value)
}

//添加任务
const addTaskRef = ref()
const onAddTask = () => {
  addTaskRef.value.open(alg.value.type)
}

// 成功后的回调函数
const onSuccess = () => {
  params.value.current = 1
  params.value.timePeriod = 1000
  params.value.stat = '全部状态'
  getChannelList()
}

// 拉取节点信息
const initNodeInfo = async () => {
  const {
    data: { data }
  } = await GetNodeByName(useStore.getNodeName())
  selectedNode.value = data
  params.value.nodeId = data.id
  getChannelList()
  getAlgDetail()
}
initNodeInfo()
</script>

<template>
  <UserBar />
  <page-container title="" v-loading="loading">
    <!-- 节点信息 + 新增任务 -->
    <template #extra>
      <div style="display: flex">
        <div class="add-task" @click="infoSearch">节点配置</div>
        <div class="add-task" @click="onAddTask">+&nbsp;&nbsp;新增任务</div>
      </div>
    </template>
    <el-row>
      <!-- 任务队列 -->
      <el-col :span="12">
        <div class="header">
          <div style="display: flex">
            <el-icon :size="26">
              <Tickets />
            </el-icon>
            <h1 style="font-size: 22px">#计算任务队列</h1>
          </div>
          <!-- 选择查询 -->
          <div>
            <el-select
              class="select_box"
              :teleported="false"
              placeholder="按时间查询"
              size="large"
              v-model="params.timePeriod"
              style="width: 150px; margin-right: 20px; color: #8091a5"
              @change="handleChange"
            >
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              class="select_box"
              :teleported="false"
              style="width: 150px"
              placeholder="按状态查询"
              v-model="params.stat"
              size="large"
              @change="handleChange"
            >
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
        <!-- 队列表 -->
        <div class="table" style="" v-if="channelList.length > 0">
          <ul
            v-for="(item, index) in channelList"
            @click="showMore(item, index)"
            :key="index"
            :style="{
              backgroundColor: activeIndex === index ? '#0C1F4A' : '#313862'
            }"
          >
            <div>
              <li style="margin-right: 10px; font-size: 16px">{{ item.id }}</li>

              <li style="margin-right: 10px; font-size: 16px">
                <img src="../../assets/icons_tasks.png" alt="" />
              </li>
              <li
                style="
                  margin-right: 10px;
                  font-size: 16px;
                  width: 100px;
                  overflow: hidden; /* 隐藏超出部分 */
                  text-overflow: ellipsis; /* 省略号 */
                "
              >
                {{ item.algType }}
              </li>
            </div>

            <div>
              <li style="margin-right: 60px; font-size: 14px">
                {{ item.ts }}
              </li>

              <li
                :style="{
                  'margin-right': '40px',
                  'font- size': '14px',
                  color:
                    item.status === 'running'
                      ? '#1ABCB0'
                      : item.status === 'end'
                      ? 'red'
                      : item.status === 'timeout'
                      ? '#FF8401'
                      : item.status === 'error'
                      ? '#E34C4C'
                      : item.status === 'pending'
                      ? 'white'
                      : ''
                }"
              >
                {{ item.status }}
              </li>
            </div>

            <div>
              <li
                @click="onRowClick(item)"
                style="
                  margin-right: 80px;
                  margin-left: 80px;
                  font-size: 14px;
                  cursor: pointer;
                "
              >
                <el-icon :size="26">
                  <Sort />
                </el-icon>
              </li>
              <li>
                <el-icon :size="26" @click="onTerminateTask(item.id)">
                  <CircleClose />
                </el-icon>
              </li>
            </div>
          </ul>
          <div class="footer">
            <el-pagination
              v-model:current-page="params.current"
              v-model:page-size="params.size"
              :page-sizes="[2, 3, 5, 10]"
              :background="true"
              layout="jumper, total, sizes, prev, pager, next"
              :total="total"
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              style="margin-top: 20px; justify-content: flex-end; color: #fff"
            />
          </div>
        </div>
        <!-- 空列表 -->
        <div v-else style="text-align: center; margin-top: 100px">
          <img
            src="../../assets/icons_without@2x.png"
            alt="Placeholder Image"
            style="max-width: 20%; height: auto; margin: 1000px, auto"
          />
          <p style="text-align: center; font-size: 18px; color: #fff">
            暂无数据
          </p>
        </div>
        <!-- 分页 -->
      </el-col>
      <!-- 任务详细 -->
      <el-col :span="11" style="margin-left: 40px">
        <h1
          v-if="channelList.length != 0"
          style="margin-bottom: 15px; font-size: 22px"
        >
          #计算任务详情信息
        </h1>
        <h1 v-else style="margin-bottom: 15px; font-size: 22px">
          无计算任务信息
        </h1>

        <taskInfo
          v-if="channelList.length != 0"
          :task="selectedTask"
          @success="onSuccess"
        ></taskInfo>
        <el-empty
          v-else
          description="请选择一项任务"
          style="color: #fff"
        ></el-empty>
      </el-col>
    </el-row>
  </page-container>

  <!-- 弹窗组件，确保 ref 和事件处理器正确绑定 -->
  <!-- 添加任务 -->
  <add-task
    ref="addTaskRef"
    @success="onSuccess"
    :algType="alg.name"
  ></add-task>

  <!-- 节点信息 -->
  <nodeInfo
    :name="selectedNode.name"
    ref="nodeInfoRef"
    @success="onSuccess"
  ></nodeInfo>
</template>

<style lang="scss" scoped>
.detailTask {
  padding: 20px 15px;
  display: flex;
  justify-content: space-between;
  background-color: rgb(23, 41, 83);
  margin-bottom: 15px;
}
/* 修改前后箭头未点击时的背景颜色 */
:deep .el-pagination .btn-prev,
:deep .el-pagination .btn-next {
  background-color: rgb(58, 65, 106) !important;
}

/* 修改未点击时的数字方块背景颜色 */
:deep .el-pagination .el-pager li:not(.active):not(.disabled):hover {
  background-color: rgb(58, 65, 106) !important;
}

/* 未点击时的数字方块背景颜色 */
:deep .el-pagination .el-pager li:not(.active):not(.disabled) {
  background-color: rgb(58, 65, 106) !important;
  color: #fff;
}

:deep .el-pagination.is-background .el-pagination__jump.is-first {
  color: #fff !important;
}

:deep .el-pagination.is-background .el-pagination__total {
  color: #fff !important;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: rgb(58, 65, 106) !important; //修改默认的背景色
  color: #fff;
}

:deep .el-input__wrapper {
  background-color: rgb(58, 65, 106) !important;
  box-shadow: 0 0 0 0 !important;
}

:deep .el-input__inner {
  color: #fff;
}
h1 {
  margin: 0;
  padding: 0;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fff;
  background-color: rgba(148, 144, 144, 0.3) 25;
}

.header {
  display: flex;
  justify-content: space-between;
  align-self: center;
}

.table {
  box-sizing: content-box;
}

ul {
  padding: 20px 20px;
  display: flex;
  align-items: stretch;
  // background-color: rgb(49, 56, 98);
  // align-content: center;
  align-self: center;
  justify-content: space-between;
}
ul div {
  display: flex;
  align-items: stretch;
}
ul li {
  list-style: none;
  // margin-bottom: 20px;
  padding: 0;
  // line-height: 60px;
}

.select_box {
  /* 默认placeholder样式 */
  :deep .el-input__inner::placeholder {
    font-size: 14px;
    font-weight: 500;
    color: #fff;
    text-align: center;
    line-height: 30px;
  }

  /* 默认框状态样式更改 */
  :deep .el-input__wrapper {
    height: 30px;
    color: #8091a5;
    background-color: #313862 !important;
    box-shadow: none !important;
    /* 使用none替代透明边框 */
  }

  /* 修改下拉框focus时的样式 */
  :deep .is-focus .el-input__wrapper {
    box-shadow: 0 0 0 1px #8091a5 inset !important;
  }

  /* 清除按钮颜色 */
  :deep .el-select__caret {
    color: #fff !important;
  }

  /* 选中字体色 */
  :deep .el-input__inner {
    color: #fff !important;
  }
}

/* 下拉框-展开样式 */
/* 展开下拉背景及边框 */
:deep .el-popper {
  background-color: #8091a5 !important;
  border: 1px solid #8091a5 !important;
}

/* 下拉项hover样式 */
.el-select-dropdown__item.hover {
  background-color: #3c6194e0 !important;
}

/* 下拉项颜色 */
.el-select-dropdown__item {
  color: #fff !important;
  text-align: center;
}

/* 箭头按钮样式（通常不需要修改背景色，只修改边框色即可） */
:deep .el-popper .el-popper__arrow::before {
  border-top-color: #fff !important;
  /* 修改箭头边框颜色 */
}
.add-task {
  width: 273px;
  height: 123px;
  text-align: center;
  line-height: 123px;
  color: #727070;
  border-radius: 3px;
  border: #727070 solid 1px;
  cursor: pointer;
  margin-left: 15px;

  &:hover {
    border-color: #fff;
    color: #fff;
  }
}
</style>
